package com.xmg.client.mgrsite.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xmg.shop.api.domain.Brand;
import com.xmg.shop.api.domain.Catalog;
import com.xmg.shop.api.service.IBrandService;
import com.xmg.shop.api.service.ICatalogService;
import com.xmg.shop.api.service.IProductService;
import com.xmg.shop.api.util.AjaxResult;
import com.xmg.shop.api.util.UploadUtil;
import com.xmg.shop.api.vo.ProductVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * Created by lenovo on 2017/11/16.
 */
@Controller
@RequestMapping("/product")
public class ProductEntryController {
    @Value("${uploadPath}")
    private String uploadPath;
    @Reference
    private IBrandService brandService;
    @Reference
    private ICatalogService catalogService;
    @Reference
    private IProductService productService;

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String productEntry(Model model) {
        List<Brand> brandList = brandService.selectAll();
        model.addAttribute("brands", brandList);
        List<Catalog> catalogList = catalogService.selectAll();
        model.addAttribute("catalogs", catalogList);
        return "product/product_input";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult productSave(ProductVo vo) {
        AjaxResult result = null;
        try {
            productService.save(vo);
            result = new AjaxResult(true,"保存成功");
        } catch (Exception e) {
            e.printStackTrace();
            result = new AjaxResult(false, "保存失败");
        }
        return result;
    }

    @RequestMapping("/upload")
    @ResponseBody
    public String productImage(MultipartFile file) {
        String fileName = UploadUtil.upload(file, uploadPath);
        return fileName;
    }
}
